package org.chen.ctrip.service.upload.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.upload.BackgroundResource;
import org.chen.ctrip.service.upload.BackgroundResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UploadServiceImpl {

    @Autowired
    private BackgroundResourceService backgroundResourceService;

    // 从配置文件读取上传路径，如果没有配置则使用默认路径
    @Value("${file.upload.path:./files}")
    private String uploadBasePath;

    // 从配置文件读取访问URL前缀
    @Value("${file.access.url.prefix:http://192.168.0.13:9001/files}")
    private String accessUrlPrefix;

    public List<BackgroundResource> uploadMultipleFiles(Collection<MultipartFile> files) {
        List<BackgroundResource> resultList = new ArrayList<>();

        for (MultipartFile file : files) {
            if (file != null && !file.isEmpty()) {
                BackgroundResource result = upload(file); // 复用你原有的单文件逻辑
                resultList.add(result);
            }
        }

        return resultList;
    }

    public BackgroundResource upload(MultipartFile file) {
        // 检查文件大小 (50MB限制)
        long fileSizeInMB = file.getSize() / (1024 * 1024);
        log.info("开始保存到本地 文件大小: {}MB", fileSizeInMB);

        if (fileSizeInMB > 50) {
            throw new RuntimeException("文件大小超过限制，最大支持50MB");
        }

        if (file.isEmpty()) {
            throw new RuntimeException("上传文件为空");
        }

        try {
            // 创建上传目录结构：uploads/年月/
            String dateFolder = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
            Path uploadDir = Paths.get(uploadBasePath, dateFolder);

            // 确保目录存在
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
                log.info("创建上传目录: {}", uploadDir);
            }

            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;
            Path filePath = uploadDir.resolve(uniqueFilename);

            // 记录开始时间
            long startTime = System.currentTimeMillis();
            log.info("开始保存文件到: {}", filePath);

            // 保存文件并显示进度
            try (InputStream inputStream = file.getInputStream();
                 OutputStream outputStream = Files.newOutputStream(filePath)) {

                byte[] buffer = new byte[8192];
                int bytesRead;
                long totalBytesRead = 0;
                long lastLogTime = System.currentTimeMillis();

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);

                    // 计算保存进度
                    totalBytesRead += bytesRead;
                    double progress = (double) totalBytesRead / file.getSize() * 100;

                    // 每秒最多记录一次日志
                    long currentTime = System.currentTimeMillis();
                    if (currentTime - lastLogTime > 1000) {
                        log.info("保存进度: {:.2f}%, 已保存: {}MB",
                                progress, totalBytesRead / (1024 * 1024));
                        lastLogTime = currentTime;
                    }
                }
            }

            // 记录结束时间
            long endTime = System.currentTimeMillis();
            log.info("文件保存完成，耗时: {}秒", (endTime - startTime) / 1000.0);

            // 构建访问URL
            String accessUrl = accessUrlPrefix + "/" + dateFolder + "/" + uniqueFilename;

            // 构建背景资源对象
            BackgroundResource backgroundResource = new BackgroundResource();
            backgroundResource.setId(UUID.randomUUID().toString());
            backgroundResource.setName(originalFilename != null ? originalFilename : uniqueFilename);
            backgroundResource.setUrl(accessUrl);
            backgroundResource.setImageKey(uniqueFilename); // 使用文件名作为key
            backgroundResource.setCreateTime(LocalDateTime.now());
            backgroundResource.setUpdateTime(LocalDateTime.now());

            // 额外设置本地路径信息（如果需要的话）
            backgroundResource.setLocalPath(filePath.toString());
            backgroundResource.setSize(file.getSize());

            // 保存到数据库
            backgroundResourceService.saveBackground(backgroundResource);
            log.info("背景资源保存成功, ID: {}, 本地路径: {}",
                    backgroundResource.getId(), filePath);

            return backgroundResource;

        } catch (IOException e) {
            log.error("保存文件到本地过程中发生错误", e);
            throw new RuntimeException("保存文件到本地失败", e);
        } catch (Exception e) {
            log.error("处理文件保存过程中发生未知错误", e);
            throw new RuntimeException("文件保存失败", e);
        }
    }
}